var express = require("express");
var router = express.Router();

let item = [
  {
    id: 1,
    loginId: "jxx",
    name: "焦",
    phone: 15788888888,
    photo: "handsome",
    role: "管理员",
    loginPwd: 123,
  },
  {
    id: 2,
    loginId: "lhl",
    name: "梁",
    phone: 18588888888,
    photo: "beautiful",
    role: "vip",
    loginPwd: 123,
  },
  {
    id: 3,
    loginId: "new",
    name: "可莉",
    phone: 15666666666,
    photo: "cute",
    role: "普通用户",
    loginPwd: 123,
  },
];
/* GET admin listing. */
router.post("/list", function (req, res) {
  res.send({ count: item.length, data: item });
});

router.post("/add", function (req, res) {
  let { name, loginId, photo, phone, role } = req.body;
  role = role ? role : "管理员";
  const data = {
    name,
    loginId,
    photo,
    phone,
    role,
    id: item.length + 1,
    loginPwd: 123,
  };
  item.push(data);
  res.send(item);
});

router.get("/getOne", function (req, res) {
  const data = item.filter((i) => {
    return i.id == req.query["id"];
  });
  res.send(data);
});

router.get("/getMine", function (req, res) {
  const data = item.filter((i) => {
    return i.loginId == req.query["loginId"];
  });
  const result = { ...data };

  res.send(result);
});

router.post("/update", function (req, res) {
  const { name, phone, photo, role } = req.body;

  item = item.map((item) => {
    if (item.loginId == req.body["loginId"]) {
      return { ...item, name, phone, photo, role };
    } else {
      return item;
    }
  });
  res.send({ ok: 1 });
});

router.post("/del", function (req, res) {
  item = item.filter((i) => {
    return i.id !== req.body["key"];
  });

  res.send({ ok: 1 });
});
// 查询
router.get("/getCheck", function (req, res) {
  if (req.query["role"] === "all") {
    res.send(item);
    return;
  }
  const data = item.filter((i) => {
    return i.role == req.query["role"];
  });
  if (data.length === 0) {
    res.send([]);
  } else {
    const data1 = item.filter((i) => {
      return i.role == data[0]["role"];
    });
    res.send(data1);
  }
});

module.exports = router;
